import axios from 'axios'
import { showFullScreenLoading, tryHideFullScreenLoading } from './requsetLoading'
import vue from 'vue'
import { Notify, Dialog } from 'vant'
import store from '@/store'
import { getPhoneNum } from '@/utils/public'
import { getToken } from '@/utils/myCookie'
import { Decrypt, Encrypt } from '@/utils/jmData'
vue.use(Notify)

function creatService(showLoading, needToken) {
    const service = axios.create({
        baseURL: VUE_APP_HNNXS_BASE_URL, // api 的 base_url
        withCredentials: true, // 跨域设置
        timeout: 60000 // 请求超时时间
    })

    service.hasKey = true // 是否已取到加密密钥
    service.needKey = true // 请求是否需要加密key
    var channel = getPhoneNum()
    let myToken = sessionStorage.getItem('mtoken')
    if (myToken != 'true' && channel != '102') {
        Dialog.alert({
            title: '温馨提示',
            message: '当前访问异常，请退出重新访问'
        }).then(() => {
            var userAgent = navigator.userAgent.toLowerCase()
            if (userAgent.match(/android_hnrcc/i) == 'android_hnrcc' || userAgent.match(/ios_hnrcc/i) == 'ios_hnrcc') {
                NXYJS.goHomePage() // eslint-disable-line
            } else {
                WeixinJSBridge.call('closeWindow') // eslint-disable-line
            }
            return
        })

    }


    //请求前拦截器
    service.interceptors.request.use(
        config => {
            service.hasKey = store.state.hasKey // 是否已取到加密密钥

            // 请求前需要设置header之类在此设置
            if (showLoading) {
                showFullScreenLoading()
            }
            config.headers['X-Requested-With'] = 'XMLHttpRequest'
            config.headers['Content-Type'] = "application/json;charset=UTF-8"
            config.headers['infoq'] = 'channelId=' + channel
            config.headers['duplicationId'] = Math.random()
            const isToken = (config.headers || {}).isToken === false
            if (needToken) {
                if (getToken() && !isToken) {
                    // // console.log('getToken() ',getToken())
                    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
                }
            }
            // 已有加密密钥及需要加密数据 才传头部 需要密钥的标识
            if (service.hasKey && service.needKey) {
                config.headers['infoe'] = 'e=a'
                    // 发送数据加密
                config.transformRequest = function(data) {
                    let d = data || ''
                    let d2 = JSON.stringify(d)
                    let d3
                    if (service.hasKey) {
                        d3 = Encrypt(d2, store.state.jmaKey)
                        return d3
                    } else {
                        return d
                    }
                }
            }
            service.needKey = true
            return config
        },
        error => {
            if (service.showLoading) {
                tryHideFullScreenLoading()
            }
            return Promise.reject(error)
        }
    )

    // response拦截器
    service.interceptors.response.use(
        response => {
            let res = response.data
                // 可做返回状态拦截处理
            if (showLoading) {
                tryHideFullScreenLoading()
            }
            if (typeof res != 'object') {
                let result = Decrypt(response.data, store.state.jmaKey)
                res = JSON.parse(result)
            }
            return res
        },
        error => {
            if (showLoading) {
                tryHideFullScreenLoading()
            }
            //错误处理
            if (error && error.response) {
                switch (error.response.status) {
                    case 400:
                        error.message = '请求错误'
                        break
                    case 403:
                        error.message = '拒绝访问'
                        break
                    case 404:
                        error.message = `请求地址出错: ${error.response.config.url}`
                        break
                    case 408:
                        error.message = '请求超时'
                        break
                    case 500:
                        error.message = '服务器内部错误'
                        break
                    case 501:
                        error.message = '服务未实现'
                        break
                    case 502:
                        error.message = '网关错误'
                        break
                    case 503:
                        error.message = '服务不可用'
                        break
                    case 504:
                        error.message = '网关超时'
                        break
                    default:
                }
            } else {
                error.message = '请求无响应，请检查您的网络'
            }
            Notify(error.message)
            return Promise.reject(error.response.data)
        }
    )
    return service
}
// 不要token
export const service = creatService(true, false)

// 不要token,不要loading
export const service2 = creatService(false, false)

// 需要token
export const request = creatService(true, true)

//要token,不要loading
export const request2 = creatService(false, true)